package component;



import javax.ws.rs.core.MediaType;

import org.springframework.stereotype.Component;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;


@Component("jerseyClient")
public class JerseyClient implements HttpClient{

    private ClientConfig clientConfig;

    public JerseyClient(){
        clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    }

    public String get(String url){
        Client writerClient = Client.create(clientConfig);
        writerClient.setConnectTimeout(3000);
        writerClient.setReadTimeout(3000);
        WebResource resource = writerClient.resource(url);
        try{
            String response =resource.accept(MediaType.APPLICATION_JSON).type(MediaType.MULTIPART_FORM_DATA).get(String.class);
            return response;
        }finally {
            writerClient.destroy();
        }

    }

    public Object get(String url,Class clazz){
        Client writerClient = Client.create(clientConfig);
        writerClient.setConnectTimeout(3000);
        writerClient.setReadTimeout(3000);
        WebResource resource = writerClient.resource(url);
        try{
            Object response =resource.accept(MediaType.APPLICATION_JSON).type(MediaType.MULTIPART_FORM_DATA).get(clazz);
            return response;
        }finally {
            writerClient.destroy();
        }

    }

    public String post(String url,String data){
        Client writerClient = Client.create(clientConfig);
        writerClient.setConnectTimeout(3000);
        writerClient.setReadTimeout(3000);
        WebResource resource = writerClient.resource(url);
        try{
            String response =resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(String.class,data);
            return response;
        }finally {
            writerClient.destroy();
        }

    }

    public Object post(String url,String data,Class clazz){
        Client writerClient = Client.create(clientConfig);
        writerClient.setConnectTimeout(3000);
        writerClient.setReadTimeout(3000);
        WebResource resource = writerClient.resource(url);
        try{
            Object response =resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).post(clazz,data);
            return response;
        }finally {
            writerClient.destroy();
        }
    }
}
